<?php

namespace App\Middleware;

use App\Exception\BusinessException;
use App\Service\WxUserService;
use Hyperf\Di\Annotation\Inject;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Server\RequestHandlerInterface;

class WxAuthMiddleware implements MiddlewareInterface
{
    public const YG_HEADER_KEY = 'yg-wx-id';

    #[Inject(WxUserService::class)]
    protected WxUserService $userService;

    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
    {
        if (!($ygHeader = $request->getHeader(self::YG_HEADER_KEY))) throw new BusinessException;

        if ($user = $this->userService->getCachedUserByOpenid($ygHeader[0])) {
            $request = $request->withAttribute('user', $user);
            return $handler->handle($request);
        } else {
            throw new BusinessException(code: 504);
        }
    }
}